package com.xc.ksxt;

import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


public class SvgToPngUtil {

    public static final String SVG=".svg";
    public static final String WMF=".wmf";
    public static final String PNG=".png";
    private static final Logger logger = LoggerFactory.getLogger(SvgToPngUtil.class);

    public static void batchWmfToPng(String src){
        Path startDirectory = Paths.get(src);
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(startDirectory, "*.wmf")) {
            for (Path path : directoryStream) {
                SvgToPngUtil.wmfToPng(path.toString());
                System.out.println("找到一个 .wmf 文件: " + path);
                // 在这里添加你想要对每个找到的.wmf文件执行的操作
            }
        } catch (IOException | TranscoderException e) {
            System.err.println("遍历目录时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
    public static void  wmfToPng(String src) throws IOException, TranscoderException {
        String svgFile=wmfToSvg(src);
        String svgCode=readToString(svgFile);
        convertToPng(svgCode,src);
    }
    public static String wmfToSvg(String src){
        InputStream in = null;
        OutputStream out = null;
        String dest = src.substring(0,
                src.lastIndexOf(WMF))
                + SVG;
        try {
            String command = "inkscape --export-filename="+dest+" "+src;
            Process p = Runtime.getRuntime().exec(command);
            p.waitFor();

        } catch (Exception e) {
            logger.error("将wmf转换为svg失败");
            throw new RuntimeException();
        }
       return dest;
    }
    private static void output(Document doc, OutputStream out) throws Exception {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
                "-//W3C//DTD SVG 1.0//EN");
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
                "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd");
        transformer.transform(new DOMSource((Node) doc), new StreamResult(out));
        if (out != null) {
            out.flush();
            out.close();
        }
    }

    public static String readToString(String fileName) {
        String encoding = "UTF-8";
        File file = new File(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return new String(filecontent, encoding);
        } catch (UnsupportedEncodingException e) {
            System.err.println("The OS does not support " + encoding);
            e.printStackTrace();
            return null;
        }
    }

    //    svg转为图片
    public static void convertToPng(String svgCode, String src) throws IOException, TranscoderException {
        String pngFilePath = src.substring(0,
                src.lastIndexOf(WMF))
                + PNG;
        File file = new File(pngFilePath);

        FileOutputStream outputStream = null;
        try {
            file.createNewFile();
            outputStream = new FileOutputStream(file);
            convertToPng(svgCode, outputStream);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    logger.error("svg转为png失败");
                    throw new RuntimeException();
                }
            }
        }
    }

    //将svgCode转换成png文件，直接输出到流中
    public static void convertToPng(String svgCode, OutputStream outputStream) throws TranscoderException, IOException {
        try {
            byte[] bytes = svgCode.getBytes(StandardCharsets.UTF_8);
            PNGTranscoder t = new PNGTranscoder();
            TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(bytes));
            TranscoderOutput output = new TranscoderOutput(outputStream);
            t.transcode(input, output);
            outputStream.flush();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    logger.error("将svgCode转换成png文件失败");
                    throw new RuntimeException();
                }
            }
        }
    }
}